<template>
  <Teleport to="body">
    <Transition name="modal">
      <div v-if="store.showModal" class="video-modal" @click.self="handleClose">
        <div class="modal-content" :style="{ clipPath: clipPathValue }">
          <div class="modal-header">
            <div class="header-left">
              <span class="modal-title">{{ store.activeCamera?.name }}</span>
              <div class="camera-info">
                <span class="info-item">{{ store.activeCamera?.location }}</span>
                <span class="info-item">{{ store.activeCamera?.resolution }}</span>
                <span class="info-item">{{ store.activeCamera?.fps }}fps</span>
                <span class="camera-status" :class="store.activeCamera?.status">
                  {{ store.activeCamera?.statusText }}
                </span>
              </div>
            </div>
            <div class="header-right">
              <el-icon class="close-icon" @click="startCloseAnimation"><Close /></el-icon>
            </div>
          </div>
          <div class="modal-body">
            <div class="large-video-container">
              <video
                v-if="store.activeCamera?.active"
                :ref="setVideoRef"
                class="large-video-player"
                preload="auto"
                controls
                autoplay
              ></video>
              <div class="camera-placeholder" v-else>
                <el-icon class="camera-icon"><VideoCamera /></el-icon>
                <span class="camera-tip">未连接</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport>
</template>

<script setup lang="ts">
import { onBeforeUnmount, ref, onMounted, watch } from 'vue'
import { VideoCamera, Close } from '@element-plus/icons-vue'
import Hls from 'hls.js'
import { useVideoMonitorStore } from '@/stores/videoMonitor'

const store = useVideoMonitorStore()
let videoPlayer: Hls | null = null
const videoRef = ref<HTMLVideoElement | null>(null)
const isClosing = ref(false)

const clipPathValue = ref('inset(0 50% 0 50%)')

// 监听弹窗显示状态
watch(() => store.showModal, (newVal) => {
  if (newVal) {
    isClosing.value = false
    // 展开动画
    const startTime = performance.now()
    const duration = 500 // 动画持续时间（毫秒）

    const animate = (currentTime: number) => {
      const elapsedTime = currentTime - startTime
      const progress = Math.min(elapsedTime / duration, 1)

      // 从中间向两边展开
      const inset = 50 - progress * 50
      clipPathValue.value = `inset(0 ${inset}% 0 ${inset}%)`

      if (progress < 1) {
        requestAnimationFrame(animate)
      }
    }

    requestAnimationFrame(animate)
  }
})

const startCloseAnimation = () => {
  if (isClosing.value) return
  isClosing.value = true

  // 收缩动画
  const startTime = performance.now()
  const duration = 500 // 动画持续时间（毫秒）

  const animate = (currentTime: number) => {
    const elapsedTime = currentTime - startTime
    const progress = Math.min(elapsedTime / duration, 1)

    // 从两边向中间收缩
    const inset = progress * 50
    clipPathValue.value = `inset(0 ${inset}% 0 ${inset}%)`

    if (progress < 1) {
      requestAnimationFrame(animate)
    } else {
      // 动画完成后关闭弹窗
      handleClose()
    }
  }

  requestAnimationFrame(animate)
}

const handleClose = () => {
  if (videoPlayer) {
    videoPlayer.destroy()
    videoPlayer = null
  }
  store.closeModal()
}

const setVideoRef = (el: any) => {
  if (!el || !store.activeCamera?.url) return

  if (Hls.isSupported()) {
    videoPlayer = new Hls({
      debug: false,
      enableWorker: true,
      lowLatencyMode: true
    })
    videoPlayer.loadSource(store.activeCamera.url)
    videoPlayer.attachMedia(el)
  } else if (el.canPlayType('application/vnd.apple.mpegurl')) {
    el.src = store.activeCamera.url
  }
}

onBeforeUnmount(() => {
  handleClose()
})
</script>

<style scoped>
.video-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(8px);
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  width: 50vw;
  height: 60vh;
  background-size: 100% 100%;
  padding: 15px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 0 30px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(51, 255, 208, 0.1);
  overflow: hidden;
  transition: clip-path 0.5s cubic-bezier(0.4, 0, 0.2, 1);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 0 15px 0;
  flex-shrink: 0;
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.modal-title {
  font-size: 20px;
  color: #33ffd0;
  font-weight: bold;
  text-shadow: 0 0 10px rgba(51, 255, 208, 0.3);
}

.camera-info {
  display: flex;
  align-items: center;
  gap: 12px;
  color: rgba(255, 255, 255, 0.8);
  font-size: 13px;
}

.info-item {
  color: rgba(255, 255, 255, 0.8);
}

.close-icon {
  font-size: 24px;
  color: #33ffd0;
  cursor: pointer;
  transition: all 0.3s;
  padding: 4px;
}

.close-icon:hover {
  transform: rotate(90deg);
  color: #fff;
}

.modal-body {
  flex: 1;
  position: relative;
  overflow: hidden;
  padding: 0;
  min-height: 0;
}

.large-video-container {
  width: 100%;
  height: 100%;
  background: #000;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
  border: 1px solid rgba(51, 255, 208, 0.3);
  box-shadow: 0 0 10px rgba(51, 255, 208, 0.1);
}

.large-video-player {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background: #000;
  filter: brightness(1.1);
}

.camera-placeholder {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: rgba(255, 255, 255, 0.7);
}

.camera-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #33ffd0;
}

.camera-tip {
  font-size: 16px;
}

.camera-status {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
}

.camera-status.online {
  background: rgba(51, 255, 208, 0.2);
  color: #33ffd0;
}

.camera-status.offline {
  background: rgba(255, 77, 79, 0.2);
  color: #ff4d4f;
}

.header-right {
  display: flex;
  align-items: center;
}

</style>
